<?php
namespace App\Third;
class Curl
{
    public static function HttpPost($url, $param='', $agent='Mozilla/4.0(CPsdk Clent1.0)')
    {/*{{{*/
        $curl=curl_init();
        curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0); //  
        curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0); //
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_POST, true); 
        curl_setopt($curl, CURLOPT_USERAGENT, $agent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_COOKIESESSION,true); 
        curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, false);
        if(is_array($param))
        {   
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
        }       
        else
        {   
            curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        }       
            
        $content = curl_exec($curl);
        curl_close($curl);    
        return $content;
    }/*}}}*/

    /** 
     * 执行一个 HTTP 请求
     *
     * @param string    $Url    执行请求的Url
     * @param mixed $Params 表单参数
     * @param string    $Method 请求方法 post / get
     * @return array 结果数组
     */
    public static function request($Url, $Params, $Method='post'){

        $Curl = curl_init();//初始化curl

        if ('get' == strtolower($Method) ) {//以GET方式发送请求
            curl_setopt($Curl, CURLOPT_URL, $Url);
        }else{//以POST方式发送请求
            curl_setopt($Curl, CURLOPT_URL, $Url);
            curl_setopt($Curl, CURLOPT_POST, 1);//post提交方式
            curl_setopt($Curl, CURLOPT_POSTFIELDS, $Params);//设置传送的参数
        }   

        curl_setopt($Curl, CURLOPT_HEADER, false);//设置header
        curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 3);//设置等待时间

        $Res = curl_exec($Curl);//运行curl
        $Err = curl_error($Curl);

        if (false === $Res || !empty($Err)){
            $Errno = curl_errno($Curl);
            $Info = curl_getinfo($Curl);
            curl_close($Curl);

            return array(
                'result' => false,
                'errno' => $Errno,
                'msg' => $Err,
                'info' => $Info,
            );  
        }   
        curl_close($Curl);//关闭curl
        return json_decode($Res, true); 
    
    }   

}
